<!doctype html>
<html>

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>聊天室</title>
	<meta http-equiv="x-ua-compatible" content="IE=edge" />
	<link rel="stylesheet" type="text/css" href="assets/css/base.css" />
	<link rel="stylesheet" type="text/css" href="assets/css/font-awesome.min.css" />
	<!-- 引入样式 -->
	<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
	<!-- 引入组件库 -->
	<script src="js/vue.min.js"></script>
	<script src="js/axios.min.js"></script>
	<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>


<body>
	<div id="app">
		<el-container>
			<el-header>
				<div class="home-header">
					<h1>简易聊天室</h1>
				</div>
			</el-header>
			<el-container>
				<el-row :gutter="20">
					<el-col :span="8">
						<!-- 用户列表侧边栏 -->
						<div class="my_ulist">
							<div class="card">
								<div class="body">
									<div class="chat-header">
										<h2>在线人数：{{UserList_Num}}</h2>
									</div>
									<div class=".m-b-20">
										<div id="u-list" class="u-list">
											<div id="chat-scroll" tabindex="1"
												style="height: 450px; overflow-y:auto; outline: none;">
												<ul id="ulist" class="chat-list list-unstyled m-b-0">
													<li v-for="(user,index) in users" :key="index" class="clearfix">
														<img v-bind:src="user.userimg" alt="avatar">
														<div class="about">
															<div class="name" v-cloak>{{user.username}}</div>
															<div class="status"><i class="fa fa-circle online"></i>
																在线
															</div>
														</div>
													</li>

												</ul>
											</div>
										</div>
									</div>

								</div>
							</div>
						</div>
					</el-col>
					<el-col :span="16">
						<!-- 聊天主窗口 -->
						<div class="my_chatbody">
							<div class="card">
								<div class="chat">
									<div class="chat-header clearfix">
										<div class="home-ico">
											<i class="fa fa-home" aria-hidden="true"></i>
										</div>
										<div class="chat-about">
											<div class="chat-with">消息窗口</div>
											<div class="chat-num-messages" v-cloak>{{welcome}}</div>
										</div>
									</div>
								</div>
								<div class="chat-box" id="mychatbox">
									<div class="card-body chat-content" tabindex="2"
										style="overflow-y:scroll; ; outline: none;">
										<div id="message">
											<div v-for="(item,index) in messageList" :key="index">
												<div v-if="item.is_Self" class="chat-item chat-left">
													<img v-bind:src="item.userimg">
													<div class="chat-details">
														<div class="chat-text" v-html="item.msg"></div>
														<div class="chat-time" v-cloak>{{item.time}}</div>
													</div>
												</div>
												<div v-else class="chat-item chat-right">
													<img v-bind:src="item.userimg">
													<div class="chat-details">
														<div class="chat-text" v-html="item.msg"></div>
														<div class="chat-time" v-cloak>{{item.time}}</div>
													</div>
												</div>
											</div>

										</div>
									</div>
									<div id="form" class="card-footer chat-form">
										<div class="chat-bar">
											<i @click="show_emot()" class="fa fa-smile-o"></i>
											<div v-if="show" class="chat-emotion">
												<ul class="emot-list clearfix">
													<li v-for="(item,index) in emot_list" :key="index">
														<img @click="select_emot(item.id)" v-bind:alt="item.id"
															v-bind:src="item.src" />
													</li>
												</ul>
											</div>
										</div>
										<div id="chat-form"><input type="text" maxlength="50" v-model="message"
												class="form-control" placeholder="输入消息">
											<button @click="sendMsg()" @keyup.enter="sendMsg()"
												class="btn btn-primary"><i class="fa fa-paper-plane"></i></button></div>
										<div class="chat-tip">
											Enter 发送消息
										</div>
									</div>
								</div>
							</div>
						</div>
					</el-col>
				</el-row>
			</el-container>
		</el-container>


	</div>
	<script src="/socket/socket.io.js"></script>
	<script>

		//var socket = io.connect('http://192.168.3.20:8081');

		// 这里的IP地址写成你自己本地localhost或本地机的IP
		var socket = io.connect('http://localhost:8082');

		new Vue({
			el: '#app',
			data: {
				message: '',
				my_img: '',
				welcome: "欢迎进入聊天室！",
				messageList: [],
				user: '',
				users: [],
				UserList_Num: 0,
				currentTime: '', //当前时间
				show: false,
				emot_num: 75,
				emot_list: []
			},
			created() {
				window.addEventListener('keydown', this.KeyUpEnter, true) //开启监听键盘按下事件
			},
			mounted: function () {
				//初始化方法
				var _this = this;
				//默认生成表情列表
				for (i = 1; i <= _this.emot_num; i++) {
					var emot = new Object()
					emot.id = i;
					emot.src = "assets/emot/" + i + ".gif";
					_this.emot_list.push(emot);
				}
				//获取后台session
				axios({
					method: 'get',
					url: '/getUserSession'
				})
					.then((res) => {
						if (res.data.code == 200) {
							//从session中获取用户信息
							if(res.data.data.username==null||res.data.data.username==""){
								return;
							}
							_this.user = res.data.data.username;
							_this.my_img = res.data.data.userimg;
							var name = _this.user;

							var userInfo = new Object();
							userInfo.username = name;
							userInfo.userimg = _this.my_img;


							//发送昵称给后端
							socket.emit("joinc2s", userInfo)
							//新用户上线提示
							socket.on("joins2c", function (data) {
								var username = data.user;
								var msg = "系统消息： " + "用户 " + username + " 进入了聊天室";
								_this.UserList_Num = data.users.length;
								_this.getCurrentTime()
								var newdata = {
									user: username,
									userimg: "assets/img/users/message.jpg",
									msg: msg,
									time: _this.currentTime,
									is_Self: true
								}
								addLine(newdata)

								_this.users = data.users
							})
							//用户下线
							socket.on("offline", (data) => {
								_this.users = data.users
								var msg = data.username + " 离开了聊天室"
								_this.UserList_Num = data.users.length
								_this.getCurrentTime()
								addLine({
									user: data.user,
									userimg: "assets/img/users/message.jpg",
									msg: msg,
									time: _this.currentTime,
									is_Self: true
								})
							})
							//从后端接收消息
							socket.on('chat message', function (data) {
								var filterdata = new Object();
								filterdata.user = data.user;
								filterdata.msg = data.msg;
								filterdata.time = data.time;
								if (data.user == _this.user) {
									data.is_Self = false
								} else {
									data.is_Self = true
								}
								addLine(data);
								_this.scrollToBottom();

							});

							//自定义添加一行信息：新上线用户
							function addLine(msg) {
								_this.messageList.push(msg);
							}

						} else {
							console.log(res.data.code)
						}
					})
					.catch(function (err) {
						console.log(err);
					})
			},
			methods: {
				sendMsg() {
					var _this = this

					if (_this.message == null || _this.message == "") {
						return;
					}
					//发消息前判断自己是否已经断线，如断线通知重新建立socketid
					var mydata = { username: _this.user, userimg: _this.my_img }

					// if (user.username != userInfo.username) {
					// 	//发送昵称给后端
					// 	socket.emit("join", userInfo)
					// }

					//向后端获取用户列表数据
					socket.emit("needUsersList", { username: _this.user, userimg: _this.my_img });
					var test;
					socket.on(_this.user, function (data) {
						
						//从服务器端拿到用户列表更新自己，
						if (data == 0) {
							alert("你已断开连接，请重新登录！")
							window.location.href = "/login"
						} 
						test = data

					});

					
						var msg = _this.user + "说: " + _this.replace_em(_this.message);
						//console.log("发送的消息内容是：" + msg)
						_this.getCurrentTime();
						var posttime = _this.currentTime

						socket.emit('chat message', {
							user: _this.user,
							userimg: _this.my_img,
							msg: msg,
							time: posttime
						});
						_this.message = "";
					
				},
				getSession() {
					var _this = this;
					//获取后台session
					axios({
						method: 'get',
						url: '/getUserSession'
					})
						.then((res) => {
							if (res.data.code == 200) {
								//从session中获取用户信息								

								var userInfo = new Object();
								userInfo.username = res.data.data.username;
								userInfo.userimg = res.data.data.userimg;

								_this.users.forEach(function (user, i) {
									if (user.username != userInfo.username) {
										//发送昵称给后端
										socket.emit("join", userInfo)
									}
								})

							} else {
								console.log(res.data.code)
							}
						})
						.catch(function (err) {
							console.log(err);
						})
				},
				sayTo(e) {
					var el = e.currentTarget;
					this.message = "";
					this.message = "对 " + el.innerHTML + " "
				},
				KeyUpEnter(e) {
					if (window.event.keyCode === 13) {
						this.sendMsg()
					}
				},
				scrollToBottom() {
					this.$nextTick(() => {
						var container = this.$el.querySelector(".chat-content");
						container.scrollTop = container.scrollHeight;
					})
				},
				getCurrentTime() {
					var _this = this;
					let hh = new Date().getHours();
					let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
					let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
					_this.currentTime = hh + ':' + mf + ':' + ss;

				},
				show_emot() {
					this.show = !this.show
				},
				select_emot(e) {
					//根据点击表情id生成快捷文字 
					var el = e
					var em_text = "[em_" + el + "]";
					//关闭表情选择器并将内容赋值到input表签内
					this.show = false;
					//console.log("test:"+em_text)
					//console.log(this.replace_em(testdata))
					this.message += em_text;

				},
				//查看显示结果
				replace_em(str) {
					str = str.replace(/\</g, '&lt;');

					str = str.replace(/\>/g, '&gt;');

					str = str.replace(/\n/g, '<br/>');

					str = str.replace(/\[em_([0-9]*)\]/g, '<img src="assets/emot/$1.gif" border="0" />');

					return str;
				}
			}
		})
	</script>
</body>

</html>